package com.hna.face.controller.business;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hna.face.base.BaseController;
import com.hna.face.common.result.BaseResult;
import com.hna.face.model.*;
import com.hna.face.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class ScheduleController extends BaseController {

	@Autowired
	IFaceScheduleService faceScheduleService;

	@Autowired
	IFaceScheduleStatService faceScheduleStatService;

	@Autowired
	IFacePersonService facePersonService;

	@Autowired
	IFaceVehicleService faceVehicleService;
	
	@Autowired
	IFaceSyncInfoService faceSyncInfoService;
	
	private final static Logger log = LoggerFactory.getLogger(ScheduleController.class);

	@RequestMapping("/schedule/index")
	public String index() {
		return "pages/schedule/index";
	}

	@RequestMapping("/schedule/add")
	public String add() {
		return "pages/schedule/add";
	}

//    @RequestMapping("/schedule/detail")
//    public ModelAndView details(HttpServletRequest request) {
//        ModelAndView modelAndView = new ModelAndView("pages/schedule/detail");
//        modelAndView.addObject("id", request.getParameter("id"));
//        return modelAndView;
//    }
//    
//    
//    @RequestMapping("/schedule/edit")
//	public ModelAndView edit(HttpServletRequest request) {
//		ModelAndView modelAndView = new ModelAndView("pages/schedule/edit");
//		modelAndView.addObject("id", request.getParameter("id"));
//		return modelAndView;
//	}
	@RequestMapping("stat/index.do")
	private String indexs() {
		return "pages/stat/index";
	}
	 
	/**
	 * 
	 * @param request
	 * @param pageInfo
	 * @param schedule
	 * @return
	 */
	@RequestMapping(value = { "/rest/schedulestat/list" }, method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> list(HttpServletRequest request, PageInfo pageInfo, ScheduleVo schedule) {
		Map<String, Object> res = new HashMap<>();
		try {
//            Wrapper<ScheduleStat> wrapper=new EntityWrapper<>();
//            if(StringUtils.isNotBlank(schedule.getStartDate())){
//        		wrapper.gt("create_time", schedule.getStartDate());
//            }
//            if(StringUtils.isNotBlank(schedule.getEndDate())){
//        		wrapper.lt("create_time", schedule.getStartDate());
//            }
//            Page<ScheduleStat> page = new Page<>(pageInfo.getPage(),pageInfo.getRows());
//            Page<ScheduleStat> scheduleList = scheduleStatService.selectPage(page, wrapper);
			if (schedule.getStartDate() == null) {
				res.put("startDate", "");
			} else {
				res.put("startDate", schedule.getStartDate());
			}
			if (schedule.getEndDate() == null) {
				res.put("endDate", "");
			} else {
				res.put("endDate", schedule.getEndDate());
			}
			Page<FaceScheduleStat> page = new Page<>(pageInfo.getPage(),pageInfo.getRows());
			Page<FaceScheduleStat> sche =this.faceScheduleStatService.selectByPage(page,res);
			res.put("rows", sche.getRecords());
			res.put("total", sche.getTotal());
			res.put("success", "true");
			return res;
		} catch (Exception e) {
			res.put("success", "false");
			return res;
		}
	}

	@RequestMapping(value = { "/rest/schedule/list" }, method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> list(HttpServletRequest request, PageInfo pageInfo, FaceSchedule faceSchedule) {
		Map<String, Object> res = new HashMap<>();
		try {
			Wrapper<FaceSchedule> wrapper = new EntityWrapper<>();
			if(StringUtils.isNotBlank(faceSchedule.getBeginTime())){
				wrapper.gt("begin_time", faceSchedule.getBeginTime());
			}
	         if(StringUtils.isNotBlank(faceSchedule.getEndTime())){
	      		wrapper.lt("begin_time", faceSchedule.getEndTime());
	        }
	         
	         if (StringUtils.isNotBlank(faceSchedule.getPersonName())) {
					wrapper.like("person_name", faceSchedule.getPersonName());
	         }
			if (StringUtils.isNotBlank(faceSchedule.getVehicleNo())) {
				wrapper.eq("vehicle_no", faceSchedule.getVehicleNo());
			}
//            if(StringUtils.isNotBlank(schedule.getMasterName())){
//        		wrapper.like("master_name", schedule.getMasterName());
//            }
			Page<FaceSchedule> page = new Page<>(pageInfo.getPage(), pageInfo.getRows());
			Page<FaceSchedule> faceScheduleList = faceScheduleService.selectPage(page, wrapper);

			res.put("rows", faceScheduleList.getRecords());
			res.put("total", faceScheduleList.getTotal());
			res.put("success", "true");
			return res;
		} catch (Exception e) {
			res.put("success", "false");
			return res;
		}
	}

	@RequestMapping("/rest/schedule/info")
	public @ResponseBody BaseResult info(HttpServletRequest request) {
		Long id = Long.parseLong(request.getParameter("id"));
		FaceSchedule faceSchedule = faceScheduleService.selectById(id);
		return BaseResult.success(faceSchedule);
	}

	@RequestMapping(value = { "/rest/schedule/del" }, method = RequestMethod.POST)
	public @ResponseBody BaseResult del(HttpServletRequest request, String ids) {
		try {

			if (StringUtils.isEmpty(ids)) {
				return BaseResult.success();
			}
			List<String> list = Arrays.asList(ids.split(","));
			faceScheduleService.deleteBatchIds(list);
			for (String id : list) {
				this.syninfo(Long.valueOf(id), 2);
			}
			return BaseResult.success();
		} catch (Exception e) {
			log.error("发生异常了", e);
			return BaseResult.fail(e.getMessage());
		}
	}

	@RequestMapping(value = { "/rest/schedule/searchPerson" }, method = RequestMethod.GET)
	public @ResponseBody BaseResult searchPerson() {

		// Map<String, Object> res = new HashMap<String, Object>();
		/*
		 * Wrapper<Schedule> wrapper = new EntityWrapper<>(); Schedule schedule = new
		 * Schedule(); wrapper.eq("beginTime",beginTime);
		 */
		Wrapper<FacePerson> wrapper = new EntityWrapper<>();
		List<FacePerson> list = facePersonService.selectList(wrapper);
//    	List<Map<String, Object>> list = faceScheduleService.getScheduleList(beginTime,endTime);
		return BaseResult.success(list);
	}

	@RequestMapping(value = { "/rest/schedule/searchVehicle" }, method = RequestMethod.GET)
	public @ResponseBody BaseResult searchVehicle() {

		// Map<String, Object> res = new HashMap<String, Object>();
		/*
		 * Wrapper<Schedule> wrapper = new EntityWrapper<>(); Schedule schedule = new
		 * Schedule(); wrapper.eq("beginTime",beginTime);
		 */
		Wrapper<FaceVehicle> wrapper = new EntityWrapper<>();
		List<FaceVehicle> list = faceVehicleService.selectList(wrapper);
//    	List<Map<String, Object>> list = faceScheduleService.getScheduleList(beginTime,endTime);
		return BaseResult.success(list);
	}

	/*
	 * @RequestMapping(value = { "/rest/schedule/save" }, method =
	 * RequestMethod.POST) public @ResponseBody BaseResult save(HttpServletRequest
	 * request,HttpServletResponse response, String scheduleNo) { Map<String,
	 * Object> res = new HashMap<>(); try { Schedule schedule = new Schedule();
	 * schedule.setScheduleNo(scheduleNo); scheduleService.insert(schedule);
	 * 
	 * return BaseResult.success(); } catch (Exception e) { log.error("发生异常了",e);
	 * return BaseResult.fail(e.getMessage()); } }
	 */

	@RequestMapping(value = { "/rest/schedule/update" }, method = RequestMethod.POST)
	public @ResponseBody BaseResult update(HttpServletRequest request, FaceSchedule faceSchedule, String meterNo) {
		Map<String, Object> res = new HashMap<>();
		try {
//        	schedule.setMeterNo(meterNo);
			faceScheduleService.updateById(faceSchedule);

//        	MjMeter meter = new MjMeter();
//        	meter.setscheduleId(schedule.getId());
//        	meter.setInstallTime(schedule.getRegisteredTime());
//        	meter.setMeterId(meterId);
//			meterService.insert(meter );
			this.syninfo(faceSchedule.getId(), 3);

			return BaseResult.success();
		} catch (Exception e) {
			log.error("发生异常了", e);
			return BaseResult.fail(e.getMessage());
		}
	}

	@RequestMapping(value = { "/rest/schedule/save" }, method = RequestMethod.POST)
	public @ResponseBody BaseResult save(FaceSchedule faceSchedule) {
		try {
			FacePerson facePerson = facePersonService.selectById(faceSchedule.getPersonId());
			FaceVehicle faceVehicle = faceVehicleService.selectById(faceSchedule.getVehicleId());

			faceSchedule.setPersonName(facePerson.getName());
			faceSchedule.setVehicleNo(faceVehicle.getVehicleNo());
			String scheduleNo=RandomUtils.nextInt(100000)+"";
			faceSchedule.setScheduleNo(scheduleNo);
			faceScheduleService.insert(faceSchedule);

			this.syninfo(faceSchedule.getId(),1);
			return BaseResult.success();
		} catch (Exception e) {
			log.error("", e);
			return BaseResult.exception(e.getMessage());
		}

	}
	private void syninfo(Long id,Integer opt) {
		FaceSchedule faceSchedule = this.faceScheduleService.selectById(id);	
		FaceSyncInfo faceSyncInfo = new FaceSyncInfo();
        faceSyncInfo.setTableName("face_schedule");
        faceSyncInfo.setRecordId(id);
        faceSyncInfo.setOpt(opt);
        faceSyncInfo.setStatus(1);
        faceSyncInfo.setVehicleId(faceSchedule.getVehicleId());
        faceSyncInfo.setVehicleNo(faceSchedule.getVehicleNo());
		faceSyncInfo.setCreateTime(new Date());
        this.faceSyncInfoService.insert(faceSyncInfo);
    }

}
